//
//  UserHistoryViewController.m
//  demoapp
//
//  Created by MingmingSun on 15/9/25.
//  Copyright (c) 2015年 pingplusplus. All rights reserved.
//

#import "UserHistoryViewController.h"
#import "PullingRefreshTableView.h"
#import "UserOrderDetailViewController.h"

@interface UserHistoryViewController ()<UITableViewDataSource,UITableViewDelegate,PullingRefreshTableViewDelegate>

@property(nonatomic,strong) NSMutableArray *barberArray;
@property(nonatomic,weak) IBOutlet PullingRefreshTableView *listView;
@property(assign,nonatomic) BOOL refreshing;
@property(assign,nonatomic) NSInteger page;

@end

@implementation UserHistoryViewController

@synthesize listView;
@synthesize refreshing = _refreshing;
@synthesize page = _page;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = @"历史订单";
        self.navigationItem.leftBarButtonItem =
        [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"arrow_white"]
                                         style:UIBarButtonItemStyleDone
                                        target:self
                                        action:@selector(backPressed:)];
        self.barberArray = [NSMutableArray array];
    }
    return self;
}

-(void)backPressed:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _page = 0;
    _refreshing = YES;
    self.listView.pullingDelegate = self;
    [self.listView awakeWhenXIB:self.listView.frame];
    [self getShowLists];
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)getShowLists{
    NSDictionary *para =
    @{@"type":@"history",
      @"max":@"10",
      @"offset":[NSString stringWithFormat:@"%i",_page * 10],
      @"token":APPALL.myUserItem.token};
    [SVProgressHUD showWithStatus:@"loading..."];
    [AVCloud callFunctionInBackground:@"order_list" withParameters:para block:^(id object, NSError *error) {
        // 执行结果
        [self.listView tableViewDidFinishedLoading];
        if (!error && object) {
            NSLog(@"avget:%@",object);
            NSDictionary *aSucData = [NSJSONSerialization JSONObjectWithData: [object dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingMutableLeaves error: &error];
            switch ([[aSucData valueForKey:@"success"] intValue]) {
                case 0:
                {
                    [tooles showGlobalAlertWithTitle:@"" andMsg:[aSucData valueForKey:@"msg"] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                }
                    break;
                case 1:
                {
                    NSLog(@"yeah1....");
                    if(_refreshing){
                        [_barberArray removeAllObjects];
                    }
                    NSArray *cityArray = [aSucData objectForKey:@"order"];
                    for (NSDictionary *dic in cityArray) {
                        [_barberArray addObject:dic];
                    }
                    [listView reloadData];
                }
                    break;
                default:
                    break;
            }
            [SVProgressHUD dismiss];
        } else {
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@", error]];
        }
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.barberArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 121.0f;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    static NSString *inde;
    inde= @"OrderHistoryID";
    cell = [tableView dequeueReusableCellWithIdentifier:inde];
    if (cell == nil) {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"OrderHistoryCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }
    UILabel *lab1 = (UILabel*)[cell viewWithTag:1];
    UILabel *lab2 = (UILabel*)[cell viewWithTag:2];
    UILabel *lab3 = (UILabel*)[cell viewWithTag:3];
    UILabel *lab4 = (UILabel*)[cell viewWithTag:4];
    UILabel *lab5 = (UILabel*)[cell viewWithTag:5];
    NSDictionary *cacheItem = [_barberArray objectAtIndex:indexPath.row];
    UIButton *but1 = (UIButton*)[cell viewWithTag:99];
    [but1 setTitle:[NSString stringWithFormat:@"%i",indexPath.row] forState:UIControlStateDisabled];
    [but1 addTarget:self action:@selector(orderPressed:) forControlEvents:UIControlEventTouchUpInside];
    UIButton *but2 = (UIButton*)[cell viewWithTag:98];
    [but2 setTitle:[NSString stringWithFormat:@"%i",indexPath.row] forState:UIControlStateDisabled];
    [but2 addTarget:self action:@selector(orderPressed:) forControlEvents:UIControlEventTouchUpInside];
    UIButton *but3 = (UIButton*)[cell viewWithTag:97];
    [but3 setTitle:[NSString stringWithFormat:@"%i",indexPath.row] forState:UIControlStateDisabled];
    [but3 addTarget:self action:@selector(orderPressed:) forControlEvents:UIControlEventTouchUpInside];
    lab1.text = [NSString stringWithFormat:@"%@-%@",[tooles replaceNullFromDic:cacheItem withKeyArray:@[@"barber"]],[tooles replaceNullFromDic:cacheItem withKeyArray:@[@"store"]]];
    lab2.text = [tooles replaceNullFromDic:cacheItem withKeyArray:@[@"status",@"name"]];
    lab3.text = [NSString stringWithFormat:@"%@,%@",[tooles replaceNullFromDic:cacheItem withKeyArray:@[@"services"]],[tooles replaceNullFromDic:cacheItem withKeyArray:@[@"hairType"]]];
    lab4.text = [NSString stringWithFormat:@"￥%@",[tooles replaceNullFromDic:cacheItem withKeyArray:@[@"dealPrice"]]];
    lab5.text = [tooles replaceNullFromDic:cacheItem withKeyArray:@[@"payTime"]];
    [tooles orderButtons:@[but1,but2,but3] byCode:[[tooles replaceNullFromDic:cacheItem withKeyArray:@[@"status",@"code"]] integerValue]];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //    NSDictionary *cacheItem = [_barberArray objectAtIndex:indexPath.row];
    return;
}

#pragma mark - PullingRefreshTableViewDelegate
- (void)pullingTableViewDidStartRefreshing:(PullingRefreshTableView *)tableView{
    self.refreshing = YES;
    self.page = 0;
    [self getShowLists];
}

- (void)pullingTableViewDidStartLoading:(PullingRefreshTableView *)tableView{
    self.refreshing = NO;
    self.page++;
    [self getShowLists];
}

#pragma mark - Scroll
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.listView tableViewDidScroll:scrollView];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    [self.listView tableViewDidEndDragging:scrollView];
}

-(void)orderPressed:(id)sender {
    NSInteger inde = [[sender titleForState:UIControlStateDisabled] integerValue];
    NSDictionary *cacheItem = [_barberArray objectAtIndex:inde];
    NSString *tit = [sender titleForState:UIControlStateNormal];
    NSLog(@"%@",tit);
    if([tit isEqualToString:@"查看详情"]){
        UserOrderDetailViewController *vc = [UserOrderDetailViewController new];
        vc.orderDic = cacheItem;
        [self.navigationController pushViewController:vc animated:YES];
        return;
    }
    if([tit isEqualToString:@""]){
        return;
    }
}

@end